<template>
  <div>
    <!-- 对话框组件绑定数据和关闭绑定close方法 -->
    <el-dialog
      :visible="showDialog"
      v-bind="$attrs"
      v-on="$listeners"
      @open="onOpen"
      @close="close"
      :title="form.id?'编辑部门':'新增部门'"
    >
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入部门编码" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择部门负责人" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in managerOptions"
              :key="index"
              :label="item.username"
              :value="item.username"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="form.introduce"
            type="textarea"
            placeholder="请输入部门介绍"
            :autosize="{minRows: 4, maxRows: 4}"
            :style="{width: '100%'}"
          />
        </el-form-item>
      </el-form>
      <!--  修改对话框的标题和按钮的据中  -->
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeesSimple } from '../../../api/employees.js'
import { getDeparments, addDepartments, updateDepartment } from '@/api/department'

export default {
  components: {},
  inheritAttrs: false,
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    node: { // 新增操作 - 父部门  子组件接收数据
      type: Object,
      required: true
    }
  },
  data() {
    const validateName = async(rule, value, callback) => {
      // 同级部门中禁止出现重复部门
      const { depts } = await getDeparments()
      const brothers = depts.filter(t => t.pid === this.node.id)
      if (brothers.find(t => t.name === value)) {
        callback(new Error('同级部门中禁止出现重复部门'))
      } else {
        callback()
      }
    }
    const validateCode = async(rule, value, callback) => {
      // 部门编码在整个模块中都不允许重复
      // 理解,当前输入部门编号,和所有的部门编号不能重复
      // 前输入部门编号
      //  this.form.code或者value
      // 所有的部门
      //  const { depts } = await getDepartments()
      // 编号不能重复,查找(find)
      const { depts } = await getDeparments()
      let result // ==> 编辑部门编码,排除自己本部门
      if (this.form.id) {
        // 编辑,排除当前自己,自己可以修改自己
        result = depts.filter(t => t.id !== this.form.id).find(t => t.code === value)
      } else {
        // 新增
        result = depts.find(t => t.code === value)
      }
      if (result) {
        callback(new Error('编号重复'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      },
      rules: {
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        }, { min: 1, max: 50, message: '1-50个字符', trigger: 'blur' }, {
          validator: validateName, trigger: blur
        }],
        code: [{
          required: true,
          message: '请输入部门编码',
          trigger: 'blur'
        }, { min: 1, max: 50, message: '1-50个字符', trigger: 'blur' }, { validator: validateCode, trigger: blur }
        ],
        manager: [{
          required: true,
          message: '请选择部门负责人',
          trigger: 'change'
        }],
        introduce: [{
          required: true,
          message: '请输入部门介绍',
          trigger: 'blur'
        }, { min: 1, max: 50, message: '1-50个字符', trigger: 'blur' }]
      },
      managerOptions: []
    }
  },
  computed: {},
  watch: {},
  async created() {
    // 获取员工列表数据
    this.managerOptions = await getEmployeesSimple()
  },
  mounted() {
  },
  methods: {
    onOpen() {
    },
    close() {
      this.$refs['formRef'].resetFields()
      this.form = {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      }
      // 关闭对话框
      this.$emit('update:showDialog', false)
    },
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          // 编辑
          await updateDepartment(this.form)
        } else {
          // 新增
          // 发请求
          await addDepartments({
            ...this.form,
            pid: this.node.id
          })
        }
        // 提示成功
        this.$message.success('操作成功')
        // 刷新列表
        this.$emit('success')
        // 关闭对话框
        this.close()
      })
    }
  }
}

</script>
<style>
</style>
